package com.bit.net.component.data.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * bit-supper-ServerConfig
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/10/11 下午 03:28
 */
@Slf4j
@Configuration
public class DataServerConfig {

    @Bean(name = "bizWorkers")
    public Executor bizWorkers() {
        int cpuProcessors = Runtime.getRuntime().availableProcessors();
        return getExecutor(
                cpuProcessors * 2,
                cpuProcessors * 4,
                512,
                "bit-supper-bizWorkers",
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private Executor getExecutor(int poolMinSize, int poolMaxSize, int queueSize, String workerName, ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(poolMinSize);
        //配置最大线程数
        executor.setMaxPoolSize(poolMaxSize);
        //配置队列大小
        executor.setQueueCapacity(queueSize);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(workerName);
        // CallerRunsPolicy：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(callerRunsPolicy);
        //执行初始化
        executor.initialize();
        return executor;
    }


}
